#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QCursor>
#include <qcursor.h>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStringList>
#include <QPainter>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setLayout(ui->verticalLayout_parent);

    initCloseDialog();
    initViews();
    getWeatherInfo();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::getWeatherInfo()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
     connect(manager, &QNetworkAccessManager::finished,this, [=](){
          qDebug() << "manger finish";
     });
     QNetworkRequest request(QUrl("http://t.weather.itboy.net/api/weather/city/101010100"));
      //如果要添加请求参数
//     QUrlQuery query;
//     query.addQueryItem("key1", "value1");
//     query.addQueryItem("key2", "value2");
//     url.setQuery(query);
     // 添加请求头
//     request.setRawHeader("Custom-Header", "HeaderValue");
     replay = manager->get(request);
     connect(replay,&QNetworkReply::finished,this,&Widget::readHttpRply);
}

void Widget::initCloseDialog()
{
    //右击关闭弹框
    menuQuit = new QMenu(this);
    QAction *openAct = new QAction(QIcon(""), tr("退出"), this);
    menuQuit->setStyleSheet("QToolTip { color: white; }");
    menuQuit->addAction(openAct);
    connect(menuQuit,&QMenu::triggered,this,[=]{
    this->close();
    });
}

void Widget::initViews()
{
    labelsQuality.push_back(ui->label_21);
    labelsQuality.push_back(ui->label_22);
    labelsQuality.push_back(ui->label_23);
    labelsQuality.push_back(ui->label_24);
    labelsQuality.push_back(ui->label_25);
    labelsQuality.push_back(ui->label_26);
    ui-> widget_4->installEventFilter(this);
    ui-> widget_5->installEventFilter(this);

}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{

    if(watched == ui->widget_4 && event->type() == QEvent::Paint){
        drawTempLineHigh();
        return  true;
    }

    if(watched == ui->widget_5 && event->type() == QEvent::Paint){
        drawTempLineLow();
        return  true;
    }
    return false;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()== Qt::RightButton){
        qDebug()<< "mouse click";
        menuQuit->exec(QCursor::pos());
    }

    //按下左键 窗口 跟随鼠标移动
    if(event->button() == Qt::LeftButton){
        mOffset = event->globalPos()-this->pos();
    }
}

int getElementAt(const std::list<int>& lst, size_t index) {
    auto it = lst.begin();
    // std::advance可以高效地增加迭代器的位置
    std::advance(it, index);
    return *it;
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - mOffset);
}

//折线图
void Widget::drawTempLineHigh()
{
   qDebug("drawTempLineHigh");
   QPainter painter(ui->widget_4);
   painter.setBrush(Qt::yellow);
   painter.setPen(Qt::yellow);
   painter.setRenderHint(QPainter::Antialiasing,true);
   int sum;
   int avg;
   for(int i = 0 ;i< 6;i++){
       sum += hightWd[i];
   }
   avg = sum / 6;
   int middle = ui->widget_4->height() / 2;

   QPoint point[6];
   for(int i =0 ;i <6 ;i++){
       point[i].setX(labelsQuality[i]->x() + labelsQuality[i]->width()/2 -10);
       qDebug() << "drawTempLineHigh"<< hightWd[i] << avg;
       point[i].setY(middle - (hightWd[i] - avg)*3);
       painter.drawEllipse(QPoint(point[i]),4,4);
   }

   for(int i= 0;i< 5;i++){
       if(i == 0){
          QPen pen(Qt::yellow);
          pen.setStyle(Qt::DotLine);
          painter.setPen(pen);
       }else{
          painter.setPen(Qt::yellow);
       }
       painter.drawLine(point[i],point[1+i]);
   }

   for(int i=0 ; i< 6;i++){
       painter.drawText(point[i].x()-10,point[i].y()-10,QString::number(hightWd[i])+"℃");
   }

}

void Widget::drawTempLineLow()
{
    qDebug("drawTempLineLow");
    QPainter painter(ui->widget_5);
    painter.setBrush(Qt::green);
    painter.setPen(Qt::green);
    painter.setRenderHint(QPainter::Antialiasing,true);
    int sum;
    int avg;
    for(int i = 0 ;i< 6;i++){
        sum += lowWd[i];
    }
    avg = sum / 6;
    int middle = ui->widget_5->height() / 2;

    QPoint point[6];
    for(int i =0 ;i <6 ;i++){
        point[i].setX(labelsQuality[i]->x() + labelsQuality[i]->width()/2 -10);
        qDebug() << "drawTempLineHigh"<< lowWd[i] << avg;
        point[i].setY(middle - (lowWd[i] - avg)*3);
        painter.drawEllipse(QPoint(point[i]),4,4);
    }

    for(int i= 0;i< 5;i++){
        if(i == 0){
           QPen pen(Qt::green);
           pen.setStyle(Qt::DotLine);
           painter.setPen(pen);
        }else{
           painter.setPen(Qt::green);
        }
        painter.drawLine(point[i],point[1+i]);
    }

    for(int i=0 ; i< 6;i++){
        painter.drawText(point[i].x()-10,point[i].y()-10,QString::number(lowWd[i])+"℃");
    }
}




//处理天气数据
void Widget::readHttpRply()
{
    int code = replay->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(replay->error() == QNetworkReply::NoError && code == 200){


        QByteArray data = replay-> readAll();
        qDebug()<< QString::fromUtf8(data);

        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject rootObj = doc.object();
        QString message = rootObj["message"].toString();
        int status = rootObj["status"].toInt();
        QString date = rootObj["date"].toString();
        QString time = rootObj["time"].toString();


        QJsonObject cityInfo = rootObj["cityInfo"].toObject();
        QString city = cityInfo["city"].toString();
        QString citykey = cityInfo["citykey"].toString();

        QJsonObject data1 = rootObj["data"].toObject();
        QString shidu = data1["shidu"].toString();
         QString quality = data1["quality"].toString();
        double pm25 = data1["pm25"].toDouble();
        qDebug()<< "PM25"<< pm25 << shidu;

        //昨天
        if(data1.contains("yesterday")){
            QJsonObject yesterday = data1["yesterday"].toObject();
            QString yhigh = yesterday["high"].toString().split(" ").at(1);
            hightWd[0]=(yhigh.split("℃").at(0).toInt());
            QString ylow = yesterday["low"].toString().split(" ").at(1);
            lowWd[0]=(ylow.split("℃").at(0).toInt());
        }


       if (data1.contains("forecast") && data1["forecast"].isArray()){
           QJsonArray forecast = data1["forecast"].toArray();
           todayInfo =  forecast.first().toObject();
           for(int i = 0; i < forecast.size(); ++i) {
               if(i < 5){
                   QJsonObject value = forecast.at(i).toObject();
                   QString yhigh = value["high"].toString().split(" ").at(1);
                   hightWd[i+1]=(yhigh.split("℃").at(0).toInt());
                   QString ylow = value["low"].toString().split(" ").at(1);
                   lowWd[i+1]=(ylow.split("℃").at(0).toInt());
               }
           }
       }


        for(int i = 0; i < 6; ++i) {
                qDebug() << "low"<< lowWd[i];
         }

        for(int i = 0; i < 6; ++i) {
                qDebug() << "hightWd"<< hightWd[i];
         }

       ui->label_type->setText(todayInfo["type"].toString());
       QString low = todayInfo["low"].toString().split(" ").at(1);
       QString hight = todayInfo["high"].toString().split(" ").at(1);
       ui->label_wendu_range->setText(low + "℃" + "-" + hight + "℃");
       ui->label_ctiyName->setText(city);
       ui->label_wind_type->setText(todayInfo["fx"].toString());
       ui->label_wind_value->setText(todayInfo["fl"].toString());
       ui->label_PM_value->setText(QString::number(pm25));
       ui->label_shidu_value->setText(shidu);
       ui->label_quality_value->setText(quality);
       ui->label_notice->setText(todayInfo["notice"].toString());

       //时间日期
       QString timeTD = todayInfo["ymd"].toString();
       QString weekTD = todayInfo["week"].toString();
       ui->label_time->setText(timeTD + " " + weekTD);

       update();

    }else{
        qDebug()<< "请求失败" << replay->errorString();
        QMessageBox::warning(this,"错误","网络请求失败",QMessageBox::Ok);
    }
}





